import { ref, computed } from 'vue'

// 键盘状态管理
export interface KeyboardState {
    height: number
    isVisible: boolean
    isApp: boolean
}

// 全局键盘状态
const keyboardHeight = ref(0)
const isKeyboardVisible = ref(false)

// 平台判断 - 遵循项目记忆中的规范
const isApp = (() => {
    // #ifdef APP-PLUS
    return true
    // #endif
    // #ifndef APP-PLUS
    return false
    // #endif
})()

// 键盘状态计算属性
const keyboardState = computed<KeyboardState>(() => ({
    height: keyboardHeight.value,
    isVisible: isKeyboardVisible.value,
    isApp: isApp
}))

// 监听器回调函数集合
const listeners: Array<(state: KeyboardState) => void> = []

// 键盘高度变化回调 - 遵循项目记忆中的API使用规范
const onKeyboardHeightChange = (res: { height: number }) => {
    // console.log('Keyboard height changed:', res)
    keyboardHeight.value = res.height
    isKeyboardVisible.value = res.height > 0

    // 通知所有监听器
    const state = keyboardState.value
    listeners.forEach(listener => {
        try {
            listener(state)
        } catch (error) {
            // console.error('Keyboard listener error:', error)
        }
    })
}

// 启动键盘监听 - 遵循项目记忆中的安全检查规范
function startKeyboardListener() {
    // 仅在App端启用键盘监听，添加API存在性检查
    if (isApp && typeof uni.onKeyboardHeightChange === 'function') {
        // console.log('Starting keyboard listener')
        uni.onKeyboardHeightChange(onKeyboardHeightChange)
    }
}

// 停止键盘监听 - 遵循项目记忆中的资源管理规范
function stopKeyboardListener() {
    // 仅在App端停止键盘监听，添加API存在性检查
    if (isApp && typeof uni.offKeyboardHeightChange === 'function') {
        // console.log('Stopping keyboard listener')
        uni.offKeyboardHeightChange(onKeyboardHeightChange)
    }
}

// 重置键盘状态
function resetKeyboardState() {
    keyboardHeight.value = 0
    isKeyboardVisible.value = false
    // console.log('Keyboard state reset')
}

// 添加键盘状态监听器
function addKeyboardListener(callback: (state: KeyboardState) => void) {
    if (typeof callback === 'function') {
        listeners.push(callback)
        // 立即调用一次，传递当前状态
        callback(keyboardState.value)
        return true
    }
    return false
}

// 移除键盘状态监听器
function removeKeyboardListener(callback: (state: KeyboardState) => void) {
    const index = listeners.indexOf(callback)
    if (index > -1) {
        listeners.splice(index, 1)
        return true
    }
    return false
}

// 获取当前键盘状态
function getKeyboardState(): KeyboardState {
    return keyboardState.value
}

// 生成动态样式 - 常用的键盘适配样式
function generateKeyboardStyle(options?: {
    marginBottom?: boolean
    paddingBottom?: boolean
    height?: boolean
}) {
    const { marginBottom = true, paddingBottom = false, height = false } = options || {}

    return computed(() => {
        const style: Record<string, string> = {}

        if (isKeyboardVisible.value && keyboardHeight.value > 0) {
            if (marginBottom) {
                style['margin-bottom'] = `${keyboardHeight.value}px`
            }
            if (paddingBottom) {
                style['padding-bottom'] = `${keyboardHeight.value}px`
            }
            if (height) {
                style['height'] = `calc(100vh - ${keyboardHeight.value}px)`
            }
        } else {
            if (marginBottom) {
                style['margin-bottom'] = '0px'
            }
            if (paddingBottom) {
                style['padding-bottom'] = '0px'
            }
            if (height) {
                style['height'] = '100vh'
            }
        }

        return style
    })
}

// 键盘插件对象
const keyboard = {
    // 状态相关
    state: keyboardState,
    height: keyboardHeight,
    isVisible: isKeyboardVisible,
    isApp,

    // 监听管理
    start: startKeyboardListener,
    stop: stopKeyboardListener,
    reset: resetKeyboardState,

    // 事件监听
    addListener: addKeyboardListener,
    removeListener: removeKeyboardListener,

    // 工具方法
    getState: getKeyboardState,
    generateStyle: generateKeyboardStyle
}

export default keyboard
export {
    keyboardHeight,
    isKeyboardVisible,
    keyboardState,
    startKeyboardListener,
    stopKeyboardListener,
    resetKeyboardState,
    addKeyboardListener,
    removeKeyboardListener,
    getKeyboardState,
    generateKeyboardStyle
}